package com.boarsoft.boar.config.server;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.boarsoft.boar.app.AppFileBiz;
import com.boarsoft.boar.config.entity.FileConfigInfo;
import com.boarsoft.boar.entity.AppFile;
import com.boarsoft.boar.entity.FileVersion;
import com.boarsoft.boar.file.FileVersionBiz;
import com.boarsoft.boar.service.FileService;
import com.boarsoft.config.file.ConfigFile;
import com.boarsoft.config.server.ConfigServerService;

@Component("configServerSvc")
public class ConfigServerServiceImpl implements ConfigServerService {
	private Logger log = LoggerFactory.getLogger(this.getClass());

	@Autowired
	protected AppFileBiz appFileBiz;
	@Autowired
	protected FileVersionBiz fileVersionBiz;
	@Autowired
	protected FileService fileSvc;

	@Override
	public boolean test() {
		return true;
	}

	@Override
	public List<ConfigFile> getConfigFiles(String appId, String env, String group) {
		List<AppFile> afLt = appFileBiz.list(appId);
		List<ConfigFile> rLt = new LinkedList<>();
		for (AppFile af : afLt) {
			FileConfigInfo c = (FileConfigInfo) af.getFile();
			ConfigFile o = new ConfigFile();
			o.setCharset(c.getCharset());
			o.setCode(c.getCode());
			o.setDeployPath(c.getDeployPath());
			o.setEncoding(c.getEncoding());
			o.setName(c.getName());
			o.setType(c.getType());
			try {
				FileVersion fv = fileVersionBiz.find(c.getId(), env, group);
				byte[] ba = fileSvc.load(fv);
				o.setContent(ba);
			} catch (IOException e) {
				log.error("Can not read config file {} for {}/{}", c.getId(), env, group, e);
				continue;
			}
			rLt.add(o);
		}
		return rLt;
	}
}